<template>
  <div class="app-container">

    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      // 1.转换格式
      // const 后端要的格式 = this.format(results, header)
      const data = this.format(results, header)
      console.log('后端要的格式', data)
      // 2.发送ajax
      try {
        const res = await importEmployee(data)
        console.log('上传的接口结果是', res)
        this.$message.success('导入成功')
        this.$router.go(-1)
      } catch (err) {
        this.$message.error(err)
      }
    },
    // return: [{ '姓名': '小王', '工号': '9002'}, { '姓名': '小张', '工号': '9001'}]

    // return: [{ 'username': '小王', 'workNumber': '9002'}, { 'username': '小张', 'workNumber': '9001'}]
    format(results, header) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      console.log(results, header)
      // rreturn []
      const res = results.map(obj => {
        // obj属性名是中文
        // 1.取出所有的属性名---> 数组
        // 2.循环数组
        //   向newObj中补充键值对
        //     键：从中文-> 英文
        //      值：obj中的值
        const newObj = {}
        const zhKeys = Object.keys(obj)
        zhKeys.forEach(zhkey => {
          const enKey = mapInfo[zhkey]
          // if(当前的key是日期相关的，要额外处理)
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // excel中的日期格式和编程语言中的格式不一样，要转换
            // newObj[enKey] = formatExcelDate(obj[zhkey])
            // 后端需要的日期格式是标准时间
            newObj[enKey] = new Date(formatExcelDate(obj[zhkey]))
          } else {
            newObj[enKey] = obj[zhkey]
          }
        })
        return newObj
      })
      return res
    }
  }
}
</script>
